import { useState } from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import { RadioGroup, Radio, Input, Button } from '@nutui/nutui-react-taro';
import { useSelector, useDispatch } from 'react-redux';
import { addTask, editTask, clearEditTask } from '../../store/taskSlice.js';
import { TASK_STATUS } from '../../const/const.js';
import './index.scss';

export default function EditDialog(props) {
  const dispatch = useDispatch();
  const editTaskItem = useSelector(state => state.task.editTaskItem);
  const [radioVal, setRadioVal] = useState(editTaskItem ? editTaskItem.status : 'undo');
  const [title, setTitle] = useState(editTaskItem ? editTaskItem.title : '');
  // 更新任务名
  const UpdateTitleValue = function(val) {
    setTitle(val);
  }
  // 更新任务状态
  const UpdateStatusValue = function(val) {
    setRadioVal(val);
  }

  // 表单表单
  const submitTask = function() {
    console.log('--submitTask--', editTaskItem);
    if (!editTaskItem) {
      // 新增
      dispatch(addTask({
        item: {
          id: Date.now(),
          title,
          status: radioVal
        }
      }))
      back();
      return;
    }
    // 修改
    dispatch(editTask({
      item: {
        ...editTaskItem,
        title,
        status: radioVal
      }
    }))
    back();
  }

  /**
   * 关闭弹框
   */
  const back = function() {
    Taro.navigateBack();
    setTimeout(() => {
      dispatch(clearEditTask());
      setRadioVal(TASK_STATUS.undo.key);
      setTitle('');
    }, 300)
  }
  return (
    <View className='task-edit-page'>
      <View className='task-edit-item'>
        <Input label="任务名：" defaultValue={editTaskItem ? editTaskItem.title : title}  placeholder="输入任务名" change={(val) => {
          UpdateTitleValue(val)
        }}/>
      </View>
      <View className='task-edit-item'>
        <RadioGroup 
          style={{width:'100%', display: 'flex', justifyContent:'space-around', paddingTop: '10px', paddingBottom: '10px' }} 
          className='tast-status-toggle' 
          value={editTaskItem ? editTaskItem.status : radioVal} 
          direction="horizontal"
          onChange = {
            (value) => {
              UpdateStatusValue(value)
            }
          }
        >
          <Radio shape="button" value="undo">{ TASK_STATUS.undo.text }</Radio>
          <Radio shape="button" value="doing">{ TASK_STATUS.doing.text }</Radio>
          <Radio shape="button" value="done">{ TASK_STATUS.done.text }</Radio>
        </RadioGroup>
      </View>
      <View className='task-edit-item task-edit-btn'>
        <Button plain type="info" className='task-btn' onClick={submitTask}>提交</Button>
      </View>
    </View>
  )
}
